<?php

namespace Mcm\RepasBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Mcm\RepasBundle\Entity\Repas;
use Mcm\RepasBundle\Entity\Commentaire;
use Mcm\RepasBundle\Form\RepasType;

/**
 * Repas controller.
 *
 */
class RepasController extends Controller {

    /**
     * Lists all Repas entities.
     *
     */
    public function indexAction() {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('McmRepasBundle:Repas')->findAll();

        return $this->render('McmRepasBundle:Repas:index.html.twig', array(
                    'entities' => $entities,
                ));
    }

    /**
     * Finds and displays a Repas entity.
     *
     */
    public function showAction($id) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('McmRepasBundle:Repas')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Repas entity.');
        }
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('McmRepasBundle:Repas:show.html.twig', array(
                    'entity' => $entity,
                    'delete_form' => $deleteForm->createView(),));
    }

    /**
     * Displays a form to create a new Repas entity.
     *
     */
    public function newAction() {
        $entity = new Repas();
        $form = $this->createForm(new RepasType(), $entity);

        return $this->render('McmRepasBundle:Repas:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
                ));
    }

    /**
     * Creates a new Repas entity.
     *
     */
    public function createAction(Request $request) {
        $entity = new Repas();
        $user = $this->container->get('security.context')->getToken()->getUser();
        $entity->setHote($user);
        $form = $this->createForm(new RepasType(), $entity);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST') {
            $form->bind($request);

            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($entity);
                var_dump($entity);
                $user->addRepashote($entity);
                var_dump($user);

                $em->merge($user);
                $em->flush();


                return $this->redirect($this->generateUrl('repas_show', array('id' => $entity->getId())));
            }
        }

        return $this->render('McmRepasBundle:Repas:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
                ));
    }

    /**
     * Displays a form to edit an existing Repas entity.
     *
     */
    public function editAction($id) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('McmRepasBundle:Repas')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Repas entity.');
        }

        $editForm = $this->createForm(new RepasType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('McmRepasBundle:Repas:edit.html.twig', array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                ));
    }

    /**
     * Edits an existing Repas entity.
     *
     */
    public function updateAction(Request $request, $id) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('McmRepasBundle:Repas')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Repas entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new RepasType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('repas_show', array('id' => $id)));
        }

        return $this->render('McmRepasBundle:Repas:edit.html.twig', array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                ));
    }

    /**
     * Deletes a Repas entity.
     *
     */
    public function deleteAction(Request $request, $id) {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('McmRepasBundle:Repas')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Repas entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('repas'));
    }

    private function createDeleteForm($id) {
        return $this->createFormBuilder(array('id' => $id))
                        ->add('id', 'hidden')
                        ->getForm()
        ;
    }

    public function rechercherAction() {
        $formBuilder = $this->createFormBuilder();
        $formBuilder
                ->add('mot', 'text');
        $form = $formBuilder->getForm();

        // On r�cup�re la requ�te
        $request = $this->get('request');

        // On v�rifie qu'elle est de type POST
        if ($request->getMethod() == 'POST') {
            // On fait le lien Requ�te <-> Formulaire
            $form->bind($request);
            $data = $form->getData();
            $liste_repas = $this->getDoctrine()
                    ->getEntityManager()
                    ->getRepository('McmRepasBundle:Repas')
                    ->mySearch($data['mot']);
            return $this->render('McmRepasBundle:Repas:index.html.twig', array(
                        'entities' => $liste_repas,
                        'mot' => $data['mot']
                    ));
        }

// � ce stade :
// - soit la requ�te est de type GET, donc le visiteur vient d'arriver sur la page et veut voir le formulaire
// - soit la requ�te est de type POST, mais le formulaire n'est pas valide, donc on l'affiche de nouveau

        return $this->render('McmRepasBundle:Recherche:rechercher.html.twig', array('form' => $form->createView(),));
    }

    public function noterFormAction($id) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('McmRepasBundle:Repas')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Repas entity.');
        }
      
        return $this->render('McmRepasBundle:Repas:noter.html.twig', array(
                    'entity' => $entity,
                ));
    }

    public function noterAction($id) {
        //on récupère le repas en cours
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('McmRepasBundle:Repas')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Repas entity.');
        }

        //on récupère l'utilisateur connecté
        $user = $this->container->get('security.context')->getToken()->getUser();
        // Et pour vérifier que l'utilisateur est authentifié (et non un anonyme)
        if (!is_object($user)) {
            throw new AccessDeniedException('Vous n\'êtes pas authentifié.');
        }
        //on récupère les valeurs saisies dans le formulaire
        $request = $this->get('request');
        if ($request->getMethod() == 'POST') {
            $contenu = $request->request->get('commentaire');
            $note = $request->request->get('notesA');

            if ($note > 0) {
                //ajout de la note au repas 
                $entity->addNote($note);
            }

            if ($contenu != "") {
                //on créé un nouveau commentaire
                $commentaire = new Commentaire();
                // on y ajoute les valeurs saisies
                $commentaire->setContenu($contenu);

                //et la date du jour
                $today = new \DateTime("now");
                $commentaire->setDate($today);
                //et l'utilisateur connecté
                $commentaire->setAuteur($user);
                $commentaire->setRepas($entity);
                //creation du commentaire en base
                $em->persist($commentaire);
                //on ajoute le commentaire au repas
                $entity->addCommentaire($commentaire);
            }
            $em->merge($entity);
            $em->flush();
            return $this->redirect($this->generateUrl('repas_show', array('id' => $entity->getId())));
        }
    
        return $this->render('McmRepasBundle:Repas:noter.html.twig', array(
                    'entity' => $entity,
                ));
    }

}
